/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
var kthSmallest = function (root, k) {
  //处理的节点数
  let count = 0
  //结果
  let res = -1

  //先序遍历
  function dfs(node) {
    if (!node) return 0

    dfs(node.left)
    count++
    if (count === k) {
      res = node.val
      return//找到后立即退出代码
    }
    //只有没找到时才递归右子树
    if (count < k) dfs(node.right)
  }
  dfs(root)

  return res
};